import { useState, useEffect, useMemo } from 'react';
import { Purchase } from 'react-native-iap';
import { Product, Subscription } from 'react-native-iap';

import { PaymentSDK } from '../core/PaymentSDK';
import { PaymentService } from '../services/PaymentService';
import type { PaymentConfig, PurchaseParams } from '../types';

/**
 * 苹果支付、谷歌支付的通用hooks，相当于支付服务的应用层
 * config 配置项，必填，包含支付服务的配置、事件回调等
 * @param config
 */
export const usePayment = (config: PaymentConfig) => {
  // 是否在处理支付中
  const [isProcessing, setIsProcessing] = useState(false);
  // 支付SDK实例
  const [sdk, setSdk] = useState<PaymentSDK | null>(null);
  // 支付基础服务（基础层）
  const [paymentService, setPaymentService] = useState<PaymentService | null>(null);

  // PaymentSDK和支付服务是否准备好
  const isPaymentReady = useMemo(() => {
    return !!sdk && !!paymentService;
  }, [sdk, paymentService]);

  useEffect(() => {
    // 初始化支付SDK
    const initSDK = async () => {
      try {
        const sdkInstance = await PaymentSDK.getInstance();
        setSdk(sdkInstance);
        const service = await PaymentService.createInstance(config);
        setPaymentService(service);
      } catch (error) {
        console.error('Failed to initialize payment:', error);
      }
    };

    initSDK();

    return () => {
      // 销毁支付SDK连接
      sdk?.endPaymentSDKConnection();
    };
  }, []);

  // 监听支付错误、支付取消
  useEffect(() => {
    if (!sdk) return;

    const errorListener = sdk.addPurchaseErrorListener((error) => {
      setIsProcessing(false);
      clearTransaction();

      if (error.code === 'E_USER_CANCELLED') {
        // 取消支付
        config.events?.onRequestPurchaseCanceled?.();
      } else {
        // 支付失败
        config.events?.onRequestPurchaseFailed?.(error);
      }
    });

    return () => {
      errorListener.remove();
    };
  }, [sdk]);

  /**
   * 进行苹果支付、谷歌支付
   * 注意：配置好参数
   * @param params
   */
  const handlePurchase = async (params: PurchaseParams) => {
    if (!paymentService) return;

    setIsProcessing(true);
    try {
      const result = await paymentService.handlePurchase(params);
      return result;
    } finally {
      setIsProcessing(false);
    }
  };

  /**
   * 恢复购买记录(仅iOS）
   */
  const restorePurchases = async () => {
    if (!paymentService) return;

    setIsProcessing(true);
    try {
      return await paymentService.restorePurchases();
    } finally {
      setIsProcessing(false);
    }
  };

  /**
   * 获取苹果/谷歌商店中的商品信息
   * @param skus
   */
  const getProductsFromStore = async (skus: string[]) => {
    if (!sdk) return [];

    try {
      return await sdk.getAllProductsFromStore(skus);
    } catch (error) {
      console.error('Failed to get products:', error);
      return [];
    }
  };

  /**
   * 获取商品价格和货币单位
   */
  const getProductPriceAndCurrency = (product?: Product | Subscription) => {
    if (!sdk || !product) return;
    return sdk.getProductPriceAndCurrency(product);
  };

  /**
   * 完成交易
   * @param purchase 购买信息
   * @param isConsumable 是否是消耗品(仅android)
   * @param developerPayloadAndroid 安卓开发者负载信息
   */
  const finishTransaction = async (purchase: Purchase, isConsumable = false, developerPayloadAndroid?: string) => {
    if (!paymentService) return;

    setIsProcessing(true);
    try {
      return await paymentService.finishTransaction(purchase, isConsumable, developerPayloadAndroid);
    } finally {
      setIsProcessing(false);
    }
  };

  /**
   * 判断是否是应用内商品
   */
  const isInappProduct = (product: Product | Subscription) => {
    if (!paymentService) return false;
    return paymentService.isInappProduct(product);
  };

  /**
   * 判断是否是订阅商品
   */
  const isSubscriptionProduct = (product: Product | Subscription) => {
    if (!paymentService) return false;
    return paymentService.isSubscriptionProduct(product);
  };

  /**
   * 清除交易记录
   */
  const clearTransaction = () => {
    PaymentService.clearTransaction();
  };

  /**
   * 获取可用的购买记录
   */
  const getAvailablePurchases = async () => {
    if (!paymentService) return [];

    setIsProcessing(true);
    try {
      const result = await paymentService.getAvailablePurchases();
      return result.data || [];
    } catch (error) {
      console.error('Failed to get available purchases:', error);
      return [];
    } finally {
      setIsProcessing(false);
    }
  };

  return {
    isPaymentReady,
    isProcessing,
    handlePurchase,
    restorePurchases,
    getProductsFromStore,
    getProductPriceAndCurrency,
    finishTransaction,
    clearTransaction,
    getAvailablePurchases,
    isInappProduct,
    isSubscriptionProduct,
  };
};
